<?php
namespace Common\Lib;

class Yeepay{
	public $platformNo = '10040011121';
	public $signUrl = "http://114.215.118.229:8088/sign";
	public $verifyUrl = "http://114.215.118.229:8088/verify";
	
	public $yeeUrl = "https://member.yeepay.com/";
	public $testUrl = "http://220.181.25.233:8081/";
	
	public $jumpApi = "member/bha/";
	public $curlApi = "member/bhaexter/bhaController";
	
	public $test = false;
	
	function __construct($test=false) {
		$this->test = $test;
		$url = $test ? $this->testUrl : $this->yeeUrl;
		$this->jumpApi = $url.$this->jumpApi;
		$this->curlApi = $url.$this->curlApi;
	}
	
	public function dojumpApi($req,$action) {
		$req = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
				.'<request platformNo="'.$this->platformNo.'">'
				.$req.'</request>';
		
		$req = str_replace("\n", '', $req);
		$sign = $this->sign($req);
		
		$html = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body>
			<form id="form" action="'.$this->jumpApi.$action.'" method="post">
			<textarea name="req" style="display:none;">'.htmlspecialchars($req).'</textarea>
			<textarea name="sign" style="display:none;">'.htmlspecialchars($sign).'</textarea>
			</form></body>
			<script language="JavaScript" type="text/JavaScript">form.submit();</script> 
			</html>';
		echo $html;
		exit();
	}
	
	public function docurlApi($req,$action) {
		$req = '<request platformNo="'.$this->platformNo.'">'.$req.'</request>';
		
		$req = str_replace("\n", '', $req);
		$sign = $this->sign($req);
		$result = $this->http_post($this->curlApi, array(
				'service' => $action,
				'req' => $req,
				'sign' => $sign,
		));
		return objectToArray(simplexml_load_string($result));
	}
	
	function http_post($url, $data) {
		$form_data = "";
		foreach($data as $key => $value) {
			if ($form_data == "") {
				$form_data = $key . "=" . rawurlencode($value);
			} else {
				$form_data = $form_data . "&" . $key . "=" . rawurlencode($value);
			}
		}
		$ch = curl_init($url);
		$rs = curl_setopt_array($ch, array(
				CURLOPT_SSL_VERIFYPEER=>false,
				CURLOPT_SSL_VERIFYHOST=>false,
				CURLOPT_POST => TRUE,
				CURLOPT_RETURNTRANSFER => TRUE,
				CURLOPT_POSTFIELDS => $form_data
		));
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}
	
	function sign($req) {
		if ($this->test) return 'xxx';
		else return $this->http_post($this->signUrl, array('req' => $req));
	}
	
	function verify($req,$sign) {
		if ($this->test) return 'SUCCESS';
		else return $this->http_post($this->verifyUrl, array('req' => $req,'sign'=>$sign));
	}
}
